package de.jmda.home.ui.vaadin.usermgmt;

import com.google.common.eventbus.EventBus;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;

import de.jmda.common.ui.web.vaadin.service.DefaultSessionContext;

public class UserLoginComponentController
{
	private Authenticator authenticator;
	private String username;

	public UserLoginComponentController(Authenticator authenticator)
  {
		this.authenticator = authenticator;
  }

	public void login(TextField tfUsername, PasswordField pfPassword)
  {
		String previousUsername = username;

		username =
				authenticator.authenticate(
						tfUsername.getValue(), pfPassword.getValue());
		
		// clear password as soon as possible
		pfPassword.setValue("");

		EventBus eventBus = DefaultSessionContext.get().getEventBus();

		if (previousUsername != null)
		{
			if (username != null)
			{
				if (false == previousUsername.equals(username))
				{
					DefaultSessionContext.get().setUsername(username);
					eventBus.post(new EventLogin(previousUsername));
				}
				else
				{
					// no user change - no login event
				}
			}
			else
			{
				// no valid login - no login event
			}
		}
		else
		{
			if (username == null)
			{
				// no valid login - no login event
			}
			else
			{
				DefaultSessionContext.get().setUsername(username);
				eventBus.post(new EventLogin(previousUsername));
			}
		}
  }

	public void loginCancel()
  {
		DefaultSessionContext.get().getEventBus().post(new EventLoginCancel());
  }
}